package com.yj.suncity.user;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import com.yj.suncity.R;
import com.yj.suncity.async.AsyncTaskUtil;
import com.yj.suncity.async.AsyncTaskUtil.ResultCallBack;
import com.yj.suncity.bean.OfferListBean;
import com.yj.suncity.bean.OfferPersonBean;
import com.yj.suncity.constant.URLCon;
import com.yj.suncity.utis.PullToRefreshView;
import com.yj.suncity.utis.ToastUtil;
import com.yj.suncity.utis.Utils;
import com.yj.suncity.utis.PullToRefreshView.OnFooterRefreshListener;
import com.yj.suncity.utis.PullToRefreshView.OnHeaderRefreshListener;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class OfferPersonListActivity extends Activity implements
		OnHeaderRefreshListener, OnFooterRefreshListener {

	private Context context;
	private String offerId;
	// private String userId;
	private ListView mListView;
	private DisplayImageOptions options;
	private ImageLoader imageLoader;

	private boolean mRefreshHeadFlag = true;// 判断是否刷新的是头部(刚开始默认是头部刷新)
	private boolean mRefreshFlag = false;// 判断是否刷新
	private PullToRefreshView mPullToRefreshView = null;
	private OfferPersonAdapter adapter;
	private List<OfferPersonBean> detailInfos;
	private int pageNum = 1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_offer_person_list);
		context = this;
		offerId = getIntent().getStringExtra("offerid");
		// userId = getIntent().getStringExtra("userid");
		options = new DisplayImageOptions.Builder()
				.showStubImage(R.drawable.android_layout_detail)
				.showImageForEmptyUri(R.drawable.android_layout_detail)
				.showImageOnFail(R.drawable.android_layout_detail)
				.cacheInMemory(true).cacheOnDisc(true)
				// .displayer(new RoundedBitmapDisplayer(10))// 设置成圆角图片
				.bitmapConfig(Bitmap.Config.RGB_565) // 设置图片的解码类型
				.build();
		findView();
		initData(1);
	}

	private void findView() {
		mPullToRefreshView = (PullToRefreshView) findViewById(R.id.main_pull_refresh_view);
		mPullToRefreshView.setOnHeaderRefreshListener(this);
		mPullToRefreshView.setOnFooterRefreshListener(this);

		mListView = (ListView) findViewById(R.id.list_view_offer_person);
		TextView emptyView = (TextView) findViewById(R.id.txt_empty);
		mListView.setEmptyView(emptyView);

	}

	private void initData(int i) {
		String path = URLCon.悬赏
				+ "?action=acceptoneofferlist&pagesize=20&pageindex=" + i
				+ "&offerid=" + offerId;
		Log.d("", "接悬赏人列表：" + path);
		AsyncTaskUtil asyncTaskUtil = new AsyncTaskUtil(context, null,
				mPullToRefreshView, mRefreshFlag, null, true, "",
				new ResultCallBack() {
					@Override
					public void JSONResult(JSONObject jsonObject) {
						OfferListBean listBean = new OfferListBean(jsonObject);
						if (mRefreshHeadFlag) {
							adapter = null;
						}
						if (adapter == null) {
							detailInfos = listBean.getPersonData();
							adapter = new OfferPersonAdapter(detailInfos);
							mListView.setAdapter(adapter);
						} else {
							detailInfos.addAll(listBean.getPersonData());
							adapter.notifyDataSetChanged();
						}
					}
				});
		asyncTaskUtil.execute(path);
	}

	class OfferPersonAdapter extends BaseAdapter {
		private List<OfferPersonBean> personBeans;

		public OfferPersonAdapter(List<OfferPersonBean> personBeans) {
			super();
			this.personBeans = personBeans;
			imageLoader = ImageLoader.getInstance();
		}

		@Override
		public int getCount() {
			return personBeans.size();
		}

		@Override
		public Object getItem(int position) {
			return personBeans.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@SuppressWarnings("deprecation")
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = getLayoutInflater().inflate(
						R.layout.adapter_offer_person_item, null);
				holder.mTxt_offer_username = (TextView) convertView
						.findViewById(R.id.txt_offer_username);
				holder.mTxt_offer_time = (TextView) convertView
						.findViewById(R.id.txt_offer_time);
				holder.mTxt_btn_finish = (TextView) convertView
						.findViewById(R.id.txt_btn_finish);
				holder.mImg_head_logo = (ImageView) convertView
						.findViewById(R.id.img_head_logo);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			final OfferPersonBean personBean = personBeans.get(position);
			holder.mTxt_offer_username.setText(personBean.getUsername());
			holder.mTxt_offer_time.setText(Utils.DateFormatDate(personBean
					.getFinish_datetime()));
			if (personBean.getIs_finish().equals("1")) {
				holder.mTxt_btn_finish.setClickable(false);
				holder.mTxt_btn_finish.setEnabled(false);
				holder.mTxt_btn_finish.setText("已完成");
				holder.mTxt_btn_finish.setBackgroundDrawable(getResources()
						.getDrawable(R.drawable.shape_orager_btn_white));
			} else {
				holder.mTxt_btn_finish.setClickable(true);
				holder.mTxt_btn_finish.setEnabled(true);
				holder.mTxt_btn_finish.setText("完成");
				holder.mTxt_btn_finish.setBackgroundDrawable(getResources()
						.getDrawable(R.drawable.shape_orager_btn));
			}
			if (!personBean.getHead_photo().equals("")) {
				imageLoader.displayImage(
						URLCon.HOST + personBean.getHead_photo(),
						holder.mImg_head_logo, options);
			} else {
				holder.mImg_head_logo
						.setImageResource(R.drawable.android_layout_detail);
			}

			holder.mTxt_btn_finish.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					finishOffer(personBean.getId());
				}
			});
			return convertView;
		}
	}

	class ViewHolder {
		TextView mTxt_offer_username;
		TextView mTxt_offer_time;
		ImageView mImg_head_logo;
		TextView mTxt_btn_finish;
	}

	public void finishOffer(String txtuserid) {
		List<NameValuePair> pairs = new ArrayList<NameValuePair>();
		String path = URLCon.悬赏;
		pairs.add(new BasicNameValuePair("action", "finishoffer"));
		pairs.add(new BasicNameValuePair("txtofferid", offerId));
		pairs.add(new BasicNameValuePair("txtuserid", txtuserid));
		Log.d("", "完成悬赏：" + path);
		AsyncTaskUtil asyncTaskUtil = new AsyncTaskUtil(context, pairs, null,
				false, null, true, "完成悬赏......", new ResultCallBack() {

					@Override
					public void JSONResult(JSONObject jsonObject) {
						if (jsonObject.optString("success").equals("1")) {
							ToastUtil.ShowToast(context, "完成悬赏！");
							mRefreshHeadFlag = true;// 判断是否刷新的是头部(刚开始默认是头部刷新)
							mRefreshFlag = false;// 判断是否刷新
							initData(1);
						} else {
							ToastUtil.ShowToast(context,
									"" + jsonObject.optString("msg"));
						}

					}
				});
		asyncTaskUtil.execute(path);
	}

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnHeadBack:
			this.finish();
			break;
		}
	}

	@Override
	public void onFooterRefresh(PullToRefreshView view) {
		mPullToRefreshView.postDelayed(new Runnable() {
			@Override
			public void run() {
				mRefreshHeadFlag = false;
				mRefreshFlag = true;
				++indexPage;
				if (indexPage > pageNum) {
					ToastUtil.ShowToast(context, "没有更多数据！");
					mPullToRefreshView.onFooterRefreshComplete();
					return;
				} else {
					initData(indexPage);
				}

				// mPullToRefreshView.onFooterRefreshComplete();
			}
		}, 1);

	}

	int indexPage = 1;

	@Override
	public void onHeaderRefresh(PullToRefreshView view) {
		mPullToRefreshView.postDelayed(new Runnable() {
			@Override
			public void run() {
				mRefreshHeadFlag = true;
				mRefreshFlag = true;
				// if (async != null) {
				// Utils.cancelTaskInterrupt(async);
				// async = null;
				// }
				indexPage = 1;// 刷新头部时将页数初始化为1
				initData(indexPage);
				// mPullToRefreshView.onHeaderRefreshComplete();
			}
		}, 1);
	}
}
